from django.shortcuts import render
from django.http import HttpResponse
from .. import models
# Create your views here.
from django.core.urlresolvers import reverse
from web.settings import BASE_DIR
import os
from django.db.models import Q
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import permission_required

#后端首页
def index(request):

    return render(request,'myadmin/index.html')

# 后台登录
def myadminlogin(request):
    if request.method == 'GET':
        # 显示一个登录的页面
        return render(request,'myadmin/login.html')
    else:
        # 执行登录

        # 判断验证码是否正确
        if request.POST['code'] != request.session['verifycode'] :
            return HttpResponse('<script>alert("验证码错误");history.back(-1);</script>')


        # 验证码用户名和密码是否正确
        # if request.POST['username'] == 'admin' and request.POST['password'] == '123456':
        #     # 执行登录
        #     # 把登录信息写入session中
        #     request.session['AdminUser'] = {'username':'admin'}
        #     return HttpResponse('<script>alert("登录成功");location.href="/myadmin/";</script>')


        # 使用django提供的后台用户验证方法
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            #登录
            login(request,user)
            return HttpResponse('<script>alert("登录成功");location.href="/myadmin/"</script>')

        return HttpResponse('<script>alert("用户名或密码不存在");location.href="/myadmin/login/"</script>')




# 后台退出登录
def myadminlogout(request):
    # request.session['AdminUser'] = ''
    # return HttpResponse('<script>alert("退出登录");location.href="/myadmin/login/";</script>')

    # 退出登录
    logout(request)
    return HttpResponse('<script>alert("退出登录成功");location.href="/myadmin/login/"</script>')

# 封装函数进行文件上传
def uploads(myfile):
    import time
    
    # myfile.name  2.jpg  jpg
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()
        
    return "/static/pics/"+filename   

# 封装分页函数
def pages(data,request):

    # 数据分页
    from django.core.paginator import Paginator

    # 实例化分页类 参数1,获取的所有的数据对象 参数2,每页显示多少条
    paginator = Paginator(data,20)

    #获取当前页码数 ?p=n
    p = request.GET.get('p',1)

    #获取当前页的数据
    lists = paginator.page(p)

    return lists

# 验证码
def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    # str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')
